package com.qfedu.repo.conntoller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.qfedu.repo.bean.Product;
import com.qfedu.repo.bean.RespResuit;

import com.qfedu.repo.common.Const;

import com.qfedu.repo.common.StreamUtils;
import com.qfedu.repo.dao.Impl.ProductDaoImpl;
import com.qfedu.repo.dao.ProductDao;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/product")
public class ProductServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding(Const.CHARACTER_ENCODING);

        String method = req.getParameter("method");
        List<Product> products = null;
        RespResuit result = new RespResuit();

        switch (method) {
            case "allList":
                products = allList();
                //专门的获取数据列表的功能代码
                if (products == null || products.isEmpty()) {
                    result.setMsg("未获取到列表数据");
                    result.setCode(Const.PRODUCT_EMPTY);
                } else {
                    result.setMsg("获取列表成功");
                    result.setCode(Const.PRODUCT_SUCCESS);
                    result.setRepo(products);
                }
                break;
            default:
                break;
        }

        //返回前端
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(result));
        writer.flush();
        writer.close();
    }


    public List<Product> allList() {
        ProductDao productDao = new ProductDaoImpl();
        return productDao.getAllList();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding(Const.CHARACTER_ENCODING);

        //获取到的前端传输的数据：json格式字符串
        //'{"pno":10010,"pname":"蛋黄派"...}'
        String reqData = StreamUtils.readStreamData(req.getInputStream());

        //反序列化
        Product product = JSON.parseObject(reqData, Product.class);
        ProductDao dao = new ProductDaoImpl();
        int flag = dao.addProduct(product);
        RespResuit result = new RespResuit();
        if (flag == 1) {
            result.setMsg("产品入库成功");
            result.setCode(Const.PRODUCT_ENTER_SUCCESS);
        } else {
            result.setMsg("产品入库失败");
            result.setCode(Const.PRODUCT_ENTER_FAILED);
        }

        //返回前端
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(result));
        writer.flush();
        writer.close();
    }
}
